import React, { useState, useEffect } from 'react';
import { useTranslation } from 'react-i18next';
import {
  UserOutlined,
  TeamOutlined,
  BankOutlined,
  BookOutlined,
  BuildOutlined,
  HomeOutlined
} from '@ant-design/icons';
import styles from './Dashboard.module.css';

interface DashboardStats {
  totalUsers: number;
  totalStudents: number;
  totalMarketingDepartments: number;
  totalClasses: number;
  totalColleges: number;
  totalDormitories: number;
  totalDormBuildings: number;
  occupancyRate: number;
  totalBeds: number;
  occupiedBeds: number;
  collegeDistribution: Array<{ name: string; count: number }>;
  marketingDistribution: Array<{ name: string; count: number }>;
  recentStudents: Array<{
    name: string;
    studentId: string;
    className: string;
    enrollmentDate: string;
  }>;
}

const Dashboard: React.FC = () => {
  const { t } = useTranslation('dashboard');
  const [stats, setStats] = useState<DashboardStats | null>(null);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    const loadDashboardData = async () => {
      try {
        const response = await fetch('/api/dashboard/stats');
        if (response.ok) {
          const data = await response.json();
          setStats(data);
        }
      } catch (error) {
        console.error(t('loadDashboardError'), error);
      } finally {
        setLoading(false);
      }
    };

    loadDashboardData();
  }, [t]);

  if (loading) {
    return (
      <div className={styles.dashboardLoading}>
        <div className={styles.loadingSpinner}>{t('common:loading')}</div>
      </div>
    );
  }

  if (!stats) {
    return (
      <div className={styles.dashboardError}>
        <p>{t('loadError')}</p>
      </div>
    );
  }

  const {
    totalUsers,
    totalStudents,
    totalMarketingDepartments,
    totalClasses,
    totalColleges,
    totalDormitories,
    totalDormBuildings,
    occupancyRate,
    totalBeds,
    occupiedBeds,
    collegeDistribution,
    marketingDistribution,
    recentStudents
  } = stats;

  return (
    <div className={styles.dashboard}>
      <div className={styles.dashboardHeader}>
        <h1>{t('title')}</h1>
        <div className={styles.dateRange}>
          {new Date().toLocaleDateString()}
        </div>
      </div>

      {/* Overview Statistics Cards */}
      <div className={styles.statsOverview}>
        <div className={styles.statCard}>
          <div className={styles.statIcon}>
            <TeamOutlined />
          </div>
          <div className={styles.statContent}>
            <h3>{t('totalStudents')}</h3>
            <div className={styles.statValue}>{totalStudents}</div>
            <div className={styles.statChange}>
              {t('activeStudents')}
            </div>
          </div>
        </div>

        <div className={styles.statCard}>
          <div className={styles.statIcon}>
            <UserOutlined />
          </div>
          <div className={styles.statContent}>
            <h3>{t('totalUsers')}</h3>
            <div className={styles.statValue}>{totalUsers}</div>
            <div className={styles.statChange}>
              {t('systemUsers')}
            </div>
          </div>
        </div>

        <div className={styles.statCard}>
          <div className={styles.statIcon}>
            <BankOutlined />
          </div>
          <div className={styles.statContent}>
            <h3>{t('collegeCount')}</h3>
            <div className={styles.statValue}>{totalColleges}</div>
            <div className={styles.statChange}>
              {t('teachingUnits')}
            </div>
          </div>
        </div>

        <div className={styles.statCard}>
          <div className={styles.statIcon}>
            <BookOutlined />
          </div>
          <div className={styles.statContent}>
            <h3>{t('classCount')}</h3>
            <div className={styles.statValue}>{totalClasses}</div>
            <div className={styles.statChange}>
              {t('teachingClasses')}
            </div>
          </div>
        </div>

        <div className={styles.statCard}>
          <div className={styles.statIcon}>
            <BuildOutlined />
          </div>
          <div className={styles.statContent}>
            <h3>{t('dormBuildings')}</h3>
            <div className={styles.statValue}>{totalDormBuildings}</div>
            <div className={styles.statChange}>
              {t('dormCount')}: {totalDormitories}
            </div>
          </div>
        </div>

        <div className={styles.statCard}>
          <div className={styles.statIcon}>
            <HomeOutlined />
          </div>
          <div className={styles.statContent}>
            <h3>{t('occupancyRate')}</h3>
            <div className={styles.statValue}>{occupancyRate}%</div>
            <div className={styles.statChange}>
              {occupiedBeds}/{totalBeds} {t('beds')}
            </div>
          </div>
        </div>
      </div>

      <div className={styles.dashboardContent}>
        {/* Left: Chart Area */}
        <div className={styles.chartsSection}>
          {/* College Student Distribution */}
          <div className={styles.chartCard}>
            <h3>{t('collegeDistribution')}</h3>
            <div className={styles.distributionChart}>
              {collegeDistribution.map((college, index) => (
                <div key={index} className={styles.distributionItem}>
                  <div className={styles.distributionLabel}>
                    <span>{college.name}</span>
                    <span>{college.count}</span>
                  </div>
                  <div className={styles.distributionBar}>
                    <div
                      className={styles.distributionFill}
                      style={{
                        width: `${(college.count / totalStudents) * 100}%`
                      }}
                    ></div>
                  </div>
                </div>
              ))}
            </div>
          </div>

          {/* Marketing Department Distribution */}
          <div className={styles.chartCard}>
            <h3>{t('marketingDistribution')}</h3>
            <div className={styles.distributionChart}>
              {marketingDistribution.map((dept, index) => (
                <div key={index} className={styles.distributionItem}>
                  <div className={styles.distributionLabel}>
                    <span>{dept.name}</span>
                    <span>{dept.count}</span>
                  </div>
                  <div className={styles.distributionBar}>
                    <div
                      className={styles.distributionFill}
                      style={{
                        width: `${(dept.count / totalStudents) * 100}%`
                      }}
                    ></div>
                  </div>
                </div>
              ))}
            </div>
          </div>
        </div>

        {/* Right: Data List */}
        <div className={styles.listsSection}>
          {/* Recently Registered Students */}
          <div className={styles.listCard}>
            <h3>{t('recentStudents')}</h3>
            <div className={styles.studentList}>
              {recentStudents.map((student, index) => (
                <div key={index} className={styles.studentItem}>
                  <div className={styles.studentAvatar}>
                    {student.name.charAt(0)}
                  </div>
                  <div className={styles.studentInfo}>
                    <div className={styles.studentName}>{student.name}</div>
                    <div className={styles.studentMeta}>
                      {student.studentId} • {student.className}
                    </div>
                  </div>
                  <div className={styles.studentDate}>
                    {new Date(student.enrollmentDate).toLocaleDateString()}
                  </div>
                </div>
              ))}
            </div>
          </div>

          {/* Marketing Statistics */}
          <div className={styles.listCard}>
            <h3>{t('marketingStats')}</h3>
            <div className={styles.departmentStats}>
              <div className={styles.statItem}>
                <span>{t('marketingCount')}:</span>
                <span>{totalMarketingDepartments}</span>
              </div>
              <div className={styles.statItem}>
                <span>{t('totalStudentsCount')}:</span>
                <span>{totalStudents}</span>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
};

export default Dashboard;